
$(function() {
    var indexObj = new ModuleIndex();
    indexObj._init();
});

function ModuleIndex() {

    var me = this;
    var record;

    this._init = function() {
        bindEvents();
        
        initDataTable();
        
        setValidation();
    };
    
    function bindEvents() {
        $('#searchBtn').on('click', function() {
            console.log('search');
            refreshDataTable();
        });

        $('#addBtn').on('click', function() {
            record = {};
            popupModal();
        });

        $('#moduleModal').on('show.bs.modal', function(e) {
            console.log('onshow');
        });

        $('#moduleModal #saveBtn').on('click', function(e) {
            saveRecord();
        });

        $('#moduleDataTable').delegate('.editBtn', 'click', function() {
            editRecord($(this).attr('row'));
        });

        $('#moduleDataTable').delegate('.deleteBtn', 'click', function() {
            deleteRecord($(this).attr('rid'));
        });
    }
    
    function initDataTable() {
        $('#moduleDataTable')
        .dataTable(
                {
                    "bProcesing" : true,
                    "bServerSide" : true,
                    "bLenthChange" : false,
                    "bFilter" : false,
                    "iDisplayLength" : 10,
                    "iDisplayStart" : 0,
                    "sEcho" : 1,
                    "bSort" : false,
                    "sAjaxSource" : contextPath + "/module/getPageInfo",
                    "fnServerParams" : function(aoData) {
                        aoData.push({
                            "name" : "codeKeyword",
                            "value" : $("#searchForm #codeKeyword").val(),
                        }, {
                            "name" : "nameKeyword",
                            "value" : $("#searchForm #nameKeyword").val(),
                        });
                    },
                    "pagingType" : "full_numbers",
                    "oLanguage" : {
                        "sLengthMenu" : "显示 _MENU_ 条记录",
                        "sSearch" : "搜索",
                        "oPaginate" : {
                            "sFirst" : "首页",
                            "sLast" : "末页",
                            "sPrevious" : "上一页",
                            "sNext" : "下一页",
                        },
                        "sEmptyTable" : "无记录",
                        "sInfo" : "共 _TOTAL_条记录，当前显示 (_START_-_END_)",
                        "sInfoFiltered" : " 共 _MAX_ 条",
                        "sLoadingRecords" : "加载中..."
                    },
                    "aoColumns" : [
                            {
                                data : 'id',
                                bVisible : false
                            },
                            {
                                data : "index0"
                            },
                            {
                                data : "code"
                            },
                            {
                                data : "name"
                            },
                            {
                                data : "remark"
                            },
                            {
                                data : null,
                                render : function(data, type, row, meta) {
                                    var html = '<div><a href="javascript:void(0);" class="editBtn margin-right-5" row="'
                                            + meta.row
                                            + '">编辑</a><a href="javascript:void(0);" class="deleteBtn" rid="'
                                            + row.id + '">删除</a></div>';
                                    return html;
                                },
                            }, ]
                });
    }

    function refreshDataTable() {
        $("#moduleDataTable").dataTable().fnDraw(false);
    }

    function editRecord(row) {
        record = $("#moduleDataTable").DataTable().row(row).data();
        popupModal();
    }

    function popupModal() {
        $('#moduleModal').modal('show');
        fillForm();
    }

    function fillForm() {
        console.log(record);
        fillJsForm('#editModuleForm', record);
    }

    function setValidation() {
        $('#editModuleForm').validate({
            rules : {
                'data.index0' : {
                    required : true,
                    digits : true,
                    max : 50
                },
                'data.code' : {
                    required : true,
                    maxlength : 20
                },
                'data.name' : {
                    required : true,
                    maxlength : 20
                },
                'data.remark' : {
                    maxlength : 100
                },
            },
            errorElement : "span",
            errorPlacement : function(error, element) {
                error.addClass("help-block");
                if (element.prop("type") === "checkbox") {
                    error.insertAfter(element.parent("label"));
                } else {
                    error.insertAfter(element);
                }
            },
            highlight : function(element, errorClass, validClass) {
                $(element).parents(".col-sm-10").addClass("has-error").removeClass("has-success");
            },
            unhighlight : function(element, errorClass, validClass) {
                $(element).parents(".col-sm-10").addClass("has-success").removeClass("has-error");
            }
        });
    }

    function saveRecord() {
        var valid = $('#editModuleForm').valid();
        console.log('validated: ' + valid);

        if (valid) {
            record = $("#editModuleForm").jsForm("get");
            console.log(record);
            var json = JSON.stringify(record);

            $.ajax({
                url : contextPath + '/module/save',
                type : 'POST',
                dataType : 'json',
                contentType : 'application/json',
                data : json,
                success : function(data) {
                    record = null;
                    if (data.success) {
                        alert('保存成功');

                        $('#moduleModal').modal('hide');
                        refreshDataTable();
                    } else {
                        alert('保存失败: ' + data.errorMessage);
                    }
                }
            });
        }
    }

    function deleteRecord(id) {
        console.log(id);
        if (!confirm('确定删除吗？')) {
            return false;
        } else {
            $.ajax({
                url : contextPath + '/module/delete?id=' + id,
                type : 'DELETE',
                dataType : 'json',
                contentType : 'application/json',
                success : function(data) {
                    if (data.success) {
                        alert('删除成功');
                        refreshDataTable();
                    } else {
                        alert('保存失败: ' + data.errorMessage);
                    }
                }
            });
            return true;
        }
    }

}
